package com.guuidea.nio.file;


import org.junit.Test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

//通过NIO 实现文件IO
public class TestNIO {


    //往本地文件中写数据
    @Test
    public void test1() throws Exception {

        //1 创建输出流
        FileOutputStream fos = new FileOutputStream("basic.txt");
        //2 从流中得到一个通道

        FileChannel fc = fos.getChannel();
        //3 提供一个缓冲区
        ByteBuffer buffer = ByteBuffer.allocate(1024);

        //4 往缓冲区中存入数据
        String str = "hello, nio";
        buffer.put(str.getBytes());
        //5 翻转缓冲区
        buffer.flip();

        //5 把缓存区写到通道中
        fc.write(buffer);
        fos.close();
    }

    @Test  //从本地文件中读取数据
    public void test2() throws Exception {

        File file = new File("basic.txt");
        //1 创建输入流
        FileInputStream fis = new FileInputStream(file);
        //2 从流中得到一个通道
        FileChannel fc = fis.getChannel();
        //3 准备缓存区
        ByteBuffer buffer = ByteBuffer.allocate((int) file.length());
        //4 从通道里读取数据并存到缓存区中
        fc.read(buffer);
        System.out.println(new String(buffer.array()));
        // 5 关闭
        fis.close();
    }

    @Test //使用NIO 实现文件的复制
    public void test3() throws Exception {
        //1 创建 输入流 输出流

        FileInputStream fis = new FileInputStream("basic.txt");
        FileOutputStream fos = new FileOutputStream("H:\\学习资料\\框架师\\NIODemo\\copy.txt");

        //2 创建两个通道


        FileChannel sourceFC = fis.getChannel();
        FileChannel descFC = fos.getChannel();

        // 3 复制文件
        descFC.transferFrom(sourceFC, 0, sourceFC.size());

        //4 关闭
        fis.close();
        fos.close();

    }

}
